# 使用摄像头

import cv2


# 立即拍摄一张照片并返回
def return_photo():
    cap = cv2.VideoCapture(0)
    ret, img = cap.read()
    cap.release()
    return img

# 立即拍摄一张照片并保存到指定路径
def capture_photo(file_path):
    cap = cv2.VideoCapture(0)
    ret, img = cap.read()
    cv2.imwrite(file_path, img)
    cap.release()

# 简单灰度化图片
def process_image(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)  # 图片灰度化
    img = cv2.equalizeHist(img)  # 直方图均衡化
    return img

# 使用级联分类器检测人脸并裁剪
def crop_image(img, cascade):
    face_cascade = cv2.CascadeClassifier(cascade)  # 加载级联分类器
    faces = face_cascade.detectMultiScale(img)  # 多尺度检测
    for (x, y, w, h) in faces:  # 遍历所有检测到的人脸
        img = img[y:y+h, x:x+w]  # 裁剪坐标为[y0:y1, x0:x1]
        return img

# 打开摄像头，按ESC关闭。
def camera_on():
    cap = cv2.VideoCapture(0)
    while (1):
        ret, frame = cap.read()
        k = cv2.waitKey(1)
        if k == 27:
            break
            # elif k == ord('s'):
            #     cv2.imwrite(
            #         'C:/Users/Levi/OneDrive/Python/opencv_test/test.jpg', frame)
            i += 1
        cv2.imshow("capture", frame)
    cap.release()
